<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="200px">
      <el-form-item label="姓名" prop="contacts">
        <el-input v-model="queryParams.contacts" placeholder="请输入姓名" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="区域" prop="areaId">
        <el-tree-select v-model="queryParams.areaId" placeholder="请选择区域" clearable :data="areaList"
          :props="defaultProps" :render-after-expand="true" class="!w-240px" />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="queryParams.mobile" placeholder="请输入手机号" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="状态" prop="isTel">
        <el-select v-model="queryParams.isTel" placeholder="请选择状态" clearable class="!w-240px">
          <el-option v-for="dict in option" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="类型" prop="resType">
        <el-select v-model="queryParams.resType" placeholder="请选择类型" clearable class="!w-240px">
          <el-option v-for="dict in Options" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" /> 搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> 重置
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="用户地址" align="center" prop="area" />
      <el-table-column label="用户手机号" align="center" prop="mobile" />
      <el-table-column label="用户姓名" align="center" prop="contacts" />
      <el-table-column label="用户性别" align="center" prop="sex" />
      <el-table-column label="是否联系" align="center" prop="isTel" />
      <el-table-column label="类型" align="center" prop="resTypeName" />
      <el-table-column label="更新时间" align="center" :formatter="dateFormatter" prop="updateTime" />
      <el-table-column label="操作" align="center" class="w-120px">
        <template #default="scope">
          <el-button type="primary" plain @click="openForm(scope.row)">
            详情
          </el-button>
          <el-button type="warning" plain @click="handleDelete(scope.row)">
            沟通
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
  </ContentWrap>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-table :data="tableData" border row-key="id" default-expand-all :tree-props="{ children: 'childrens' }"
      style="width: 100%; margin-top: 20px">
      <el-table-column prop="fieldDesc" label="功能类型" width="400" />
      <el-table-column prop="fieldValue" label="是否选中" />
    </el-table>
  </Dialog>
  <Dialog :title="dialogShowInputTitle" v-model="dialogShowInput"
    style="display: block;flex-direction: column;width: 700px;">
    <div>沟通状态:
      <el-radio-group v-model="radio1" style="margin-left: 50px;" @change="changeRadio">
        <el-radio value="0" size="large" style="margin-right: 100px;">未联系</el-radio>
        <el-radio value="1" size="large">已联系</el-radio>
      </el-radio-group>
    </div>
    <div style="display: flex;margin-top: 30px;">沟通详情:
      <el-input v-model="textarea" style="width: 500px;margin-left: 50px;" :autosize="{ minRows: 4, maxRows: 100 }"
        :rows="2" type="textarea" placeholder="请输入沟通详情" @change="changeInput" />
    </div>
    <template #footer>
      <el-button @click="submitForm" type="primary">提交</el-button>
      <el-button @click="rejectSubmit">取消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { customizationApi } from '@/api/member/customization'
import { dateFormatter } from '@/utils/formatTime'
import * as AreaApi from '@/api/system/area'
import { defaultProps } from '@/utils/tree'
const queryParams = reactive({
  pageNo: 1,
  pageSize: 20,
  resType: undefined,
  isTel: undefined,
  mobile: undefined,
  areaId: undefined,
  contacts: undefined
})
const message = useMessage()
const loading = ref(false)
const list = ref([])
const total = ref(0)
let tableData = ref([])
const queryFormRef = ref() // 搜索的表单
const textarea = ref('')
const areaList = ref([])
const radio1 = ref('')
const isTel = ref(1)
const id = ref('')
const dialogTitle = ref('定制详情')
const dialogShowInputTitle = ref('沟通详情')
const dialogVisible = ref(false)
const dialogShowInput = ref(false)
const option = reactive([
  { value: 1, label: '已联系' },
  { value: 0, label: '未联系' }
])
const Options = reactive([
  { value: 0, label: '官网' },
  { value: 1, label: '餐饮' },
  { value: 2, label: '酒店' },
  { value: 3, label: '全行业' }
])
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}
const rejectSubmit = () => {
  dialogShowInput.value = false
}
const openForm = async (row: any) => {
  dialogVisible.value = true;
  const queryParamsTree = reactive({
    pageNo: 1,
    pageSize: 20
  });

  try {
    const data = await customizationApi.getDataTree(queryParamsTree);
    const foundItem = data.find((item) => item.fieldName.includes(row.resTypeName));
    if (foundItem && foundItem.childrens) {
      // 解析 JSON 字符串
      const jsonObject = JSON.parse(row.result); // 确保 row.result 是一个 JSON 字符串
      console.log('1', jsonObject);
      // 遍历 foundItem 的 childrens
      Object.entries(jsonObject).forEach(([key, value]) => {
        foundItem.childrens.forEach((cos: any) => {
          if (cos.id == key) {
            cos.fieldValue = value // 更新 fieldValue
          }
          cos.childrens.forEach((num: any) => {
            if (num.fieldValue === null) {
              num.fieldValue = '否'
            }
            if (num.id == key) {
              num.fieldValue = value === 1 ? '是' : value; // 更新 fieldValue
            }
          });
        });
      });

      // 更新 tableData
      tableData.value = foundItem.childrens;
    } else {
      tableData.value = [];
    }
  } catch (error) {
    console.error('获取数据失败：', error);
  }
};
const handleDelete = async (row: any) => {
  id.value = row.id
  dialogShowInput.value = true
  console.log('18', row);
  dialogShowInput.value = row.telRes === null ? '' : row.telRes
  radio1.value = row.isTel === '已联系' ? '1' : '0'
  textarea.value = row.telRes
  // ElMessageBox.confirm(
  //   '请确认已线下转账成功，此操作会扣除代理商收入余额',
  //   '提示',
  //   {
  //     confirmButtonText: '确定',
  //     cancelButtonText: '取消',
  //     type: 'warning',
  //   }
  // )
  //   .then(() => {
  //     clickFinish(row)
  //   })
  //   .catch(() => {
  //     console.log('用户点击取消');

  //   })

}
// const clickFinish = async (row) => {
//   try {
//     const list = {
//       id: row.id,
//       applyStatus: 4,
//     }
//     const data = await customizationApi.getCustomizationPage(list)
//     if (data === true) {
//       message.success('审核成功')
//       getList()
//     } else {
//       message.error('请求错误')
//     }
//   } finally {
//     dialogVisible.value = false
//   }
// }

const getList = async () => {
  loading.value = true
  try {
    const data = await customizationApi.getCustomizationPage(queryParams)
    areaList.value = await AreaApi.getAreaTree()
    const dataList = data.list.map((item) => {
      item.resTypeName = item.resType === 0 ? '官网' : item.resType === 1 ? '餐饮' : item.resType === 2 ? '酒店' : '全行业'
      item.isTel = item.isTel === 1 ? '已联系' : '未联系'
      return item
    })
    list.value = dataList
    total.value = data.total
  } finally {
    loading.value = false
  }
}
const changeRadio = (event: any) => {
  isTel.value = Number(event)
}

const changeInput = (event: any) => {
  textarea.value = event
}
const submitForm = async () => {
  const querydata = {
    id: id.value,
    isTel: isTel.value,
    telRes: textarea.value
  }
  try {
    const data = await customizationApi.updateCustomization(querydata)
    console.log('data', data);
    if (data === true) {
      message.success('修改成功')
      getList()
    } else {
      message.success(data.msg)
    }
  } catch {
    console.log('错误');
  } finally {
    dialogShowInput.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>